package com.example.administrator.musicplay;

/**
 * Created by winner on 2018/10/10.
 */

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.data.Music;
import com.example.administrator.data.MusicList;
import com.example.administrator.model.PropertyBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    // 显示组件
    private ImageButton imgBtn_Previous;
    private ImageButton imgBtn_PlayOrPause;
    private ImageButton imgBtn_Stop;
    private ImageButton imgBtn_Next;
    private ImageButton imgBtn_Mode;
    private ListView listView;
    private RelativeLayout root_Layout;
    private TextView tv_current_time;
    private TextView tv_total_time;
    private SeekBar seekBar;

    //歌曲列表对象
    private ArrayList<Music> musicArrayList;

    //退出判断标记
    private static boolean isExit =false;

    // 当前歌曲的序号，下标从0开始
    private int number = 0;

    //播放状态
    private int status;

    //广播接收器
    private StatusChangedReceiver receiver;

    //进度条
    private Handler seekBarHandler;

    //当前歌曲的持续时间和当前位置，作用于进度条
    private int duration;
    private int time;

    //进度条控制常量
    private static final int PROGRESS_INCREASE = 0;
    private static final int PROGRESS_PAUSE = 1;
    private static final int PROGRESS_RESET = 2;

    //播放模式常量
    private int playmode;
    private int play=0;
    private static final int MODE_LIST_SEQUENCE = 0;
    private static final int MODE_SINGLE_CYCLE = 1;
    private static final int MODE_LIST_CYCLE = 2;
    private static final int MODE_LIST_RANDOM = 3;

    //音量控制
    private TextView tv_vol;
    private SeekBar seekbar_vol;

    //睡眠模式相关组件，标识常量
    private ImageView iv_sleep;
    private Timer timer_sleep;
    private static final boolean NOTSLEEP = false;
    private static final boolean ISSLEEP = true;

    //默认睡眠时间
    private int sleepminute = 20;

    //标记是否打开睡眠模式
    private static  boolean sleepmode;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //显示组件
        findViews();
        registerListeners();
        //获取歌曲
        initMusicList();
        initListView();
        checkMusicfile();
        //进度时间
        duration = 0;
        time = 0;
        //绑定广播接收器，可以接收广播
        bindStatusChangedReceiver();
        //进度条
        initSeekBarHandler();
        //按钮绑定服务
        startService(new Intent(this, MusicService.class));
        //默认歌曲状态是停止
        status = MusicService.COMMAND_STOP;
        //默认播放模式是顺序播放
        playmode = MainActivity.MODE_LIST_SEQUENCE;
        //默认睡眠模式为关闭状态
        sleepmode = MainActivity.NOTSLEEP;
    }

    //获取显示组件
    void findViews()
    {
        listView = (ListView) findViewById(R.id.main_listview);
        tv_current_time = (TextView) findViewById(R.id.main_tv_current);
        tv_total_time = (TextView) findViewById(R.id.main_tv_total);
        imgBtn_Previous = (ImageButton) findViewById(R.id.main_btn_pre);
        imgBtn_PlayOrPause = (ImageButton) findViewById(R.id.main_btn_play);
        imgBtn_Previous = (ImageButton) findViewById(R.id.main_btn_pre);
        imgBtn_Next = (ImageButton) findViewById(R.id.main_btn_next);
        imgBtn_Stop = (ImageButton) findViewById(R.id.main_btn_stop);
        imgBtn_Mode = (ImageButton)findViewById(R.id.main_btn_mode);
        seekBar = (SeekBar) findViewById(R.id.main_seekBar);
        root_Layout = (RelativeLayout) findViewById(R.id.relativeLayout1);
        tv_vol = (TextView)findViewById(R.id.main_tv_volume);
        seekbar_vol = (SeekBar)findViewById(R.id.main_sb_volume);
        iv_sleep = (ImageView) findViewById(R.id.main_iv_sleep);
    }

    //为显示组件注册监听器
    private void registerListeners()
    {
        //更换播放模式
        imgBtn_Mode.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v)
            {
                switch(playmode)
                {
                    //顺序播放
                    case MODE_LIST_SEQUENCE:
                        playmode=MODE_SINGLE_CYCLE;
                        imgBtn_Mode.setBackgroundResource(R.drawable.button_single_cycle);
                        Toast.makeText(MainActivity.this,R.string.singlecycle,Toast.LENGTH_SHORT).show();
                        break;
                    //单曲循环
                    case MODE_SINGLE_CYCLE:
                        playmode=MODE_LIST_CYCLE;
                        imgBtn_Mode.setBackgroundResource(R.drawable.button_list_cycle);
                        Toast.makeText(MainActivity.this,R.string.listcycle,Toast.LENGTH_SHORT).show();
                        break;
                    //列表循环
                    case MODE_LIST_CYCLE:
                        playmode=MODE_LIST_RANDOM;
                        imgBtn_Mode.setBackgroundResource(R.drawable.button_list_random);
                        Toast.makeText(MainActivity.this,R.string.random,Toast.LENGTH_SHORT).show();
                        break;
                    //随机播放
                    case MODE_LIST_RANDOM:
                        playmode=MODE_LIST_SEQUENCE;
                        imgBtn_Mode.setBackgroundResource(R.drawable.button_list_sequence);
                        Toast.makeText(MainActivity.this,R.string.sequence,Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
            }
        });
        //上一首
        imgBtn_Previous.setOnClickListener(new OnClickListener() {
            public void onClick(View view)
            {
                switch(playmode)
                {
                    case MainActivity.MODE_LIST_CYCLE:
                        if (number == 0)
                        {
                            number = musicArrayList.size()-1;
                            sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        }
                        else
                            sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);
                        break;
                    case MainActivity.MODE_LIST_RANDOM:
                        sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
                        break;
                    default:
                        sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);
                        break;
                }
            }
        });
        //播放/暂停
        imgBtn_PlayOrPause.setOnClickListener(new OnClickListener() {
            public void onClick(View view)
            {
                switch (status)
                {
                    case MusicService.STATUS_PLAYING:
                        sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        break;
                    case MusicService.STATUS_PAUSED:
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        break;
                    case MusicService.STATUS_STOPPED:
                        number=0;
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    default:
                        break;
                }
            }
        });
        //停止
        imgBtn_Stop.setOnClickListener(new OnClickListener() {
            public void onClick(View view)
            {
                sendBroadcastOnCommand(MusicService.COMMAND_STOP);
            }
        });
        //下一首
        imgBtn_Next.setOnClickListener(new OnClickListener() {
            public void onClick(View view)
            {
                switch(playmode)
                {
                    case MainActivity.MODE_LIST_CYCLE:
                        if (number == musicArrayList.size() - 1)
                        {
                            number = 0;
                            sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        }
                        else
                            sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                        break;
                    case MainActivity.MODE_LIST_RANDOM:
                        sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
                        break;
                    default:
                        sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                        break;
                }
            }
        });
        //列表
        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                number = position;
                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
            }
        });
        //进度条
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar)
            {
                if(status != MusicService.STATUS_STOPPED)
                {
                    time =seekBar.getProgress();
                    //更新文本
                    tv_current_time.setText(formatTime(time));
                    //发送广播给MusicService,执行跳转
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                }
                if(status == MusicService.STATUS_PLAYING)
                {
                    //发送广播给MusicService，执行跳转
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    //进度条恢复移动
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }
                if(status ==MusicService.STATUS_PAUSED)
                {
                    time =seekBar.getProgress();
                    tv_current_time.setText(formatTime(time));
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar)
            {
                //进度条暂停移动
                seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
            }
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }
        });
    }

    //初始化音乐列表对象
    private void initMusicList()
    {
        musicArrayList = MusicList.getMusicList();
        //避免重复添加音乐
        if (musicArrayList.isEmpty())
        {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                    MediaStore.Audio.AudioColumns.TITLE);
            //标题
            int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
            //艺术家
            int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
            //总时长
            int indexDuration = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
            //路径
            int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);

            //通过mMusicCursor游标遍历数据库，并将Music类对象加载到ArrayList中
            for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor.moveToNext())
            {
                String strTitle = mMusicCursor.getString(indexTitle);
                String strArtist = mMusicCursor.getString(indexArtist);
                String strDuration = mMusicCursor.getString(indexDuration);
                String strPath = mMusicCursor.getString(indexPath);

                if (strArtist.equals("<unknown>"))
                {
                    strArtist = "未知艺术家";
                    Music music = new Music(strTitle, strArtist, strPath, strDuration);
                    musicArrayList.add(music);
                } else {
                    Music music = new Music(strTitle, strArtist, strPath, strDuration);
                    musicArrayList.add(music);
                }
            }
        }
    }

    //设置适配器并初始化列表
    private void initListView()
    {
        List<Map<String, String>> list_map = new ArrayList<>();
        HashMap<String, String> map;
        SimpleAdapter simpleAdapter;
        //遍历音乐列表
        for (Music music : musicArrayList)
        {
            map = new HashMap<>();
            map.put("musicName", music.getmusicName());
            map.put("musicArtist", music.getmusicArtist());
            list_map.add(map);
        }

        String[] from = new String[]{"musicName", "musicArtist"};
        int[] to = {R.id.listview_tv_title_item, R.id.listview_tv_artist_item};

        simpleAdapter = new SimpleAdapter(this, list_map, R.layout.listview, from, to);
        listView.setAdapter(simpleAdapter);
    }

    //判断列表是否有歌曲
    private void checkMusicfile()
    {
        if (musicArrayList.isEmpty())
        {
            imgBtn_Next.setEnabled(false);
            imgBtn_PlayOrPause.setEnabled(false);
            imgBtn_Previous.setEnabled(false);
            imgBtn_Stop.setEnabled(false);
            Toast.makeText(getApplicationContext(), "当前没有歌曲文件", Toast.LENGTH_SHORT).show();
        } else {
            imgBtn_Next.setEnabled(true);
            imgBtn_PlayOrPause.setEnabled(true);
            imgBtn_Previous.setEnabled(true);
            imgBtn_Stop.setEnabled(true);
        }
    }

    //绑定广播接收器，接收歌曲播放状态
    private void bindStatusChangedReceiver()
    {
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter(
                MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver, filter);
    }

    //发送命令来控制歌曲
    private void sendBroadcastOnCommand(int command)
    {
        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        //根据不同命令，封装不同的数据
        switch (command)
        {
            case MusicService.COMMAND_PLAY:
                intent.putExtra("number", number);
                break;
            case MusicService.COMMAND_SEEK_TO:
                intent.putExtra("time",time);
                break;
            case MusicService.COMMAND_PREVIOUS:
            case MusicService.COMMAND_NEXT:
            case MusicService.COMMAND_PAUSE:
            case MusicService.COMMAND_STOP:
            case MusicService.COMMAND_RESUME:
            case MusicService.COMMAND_RANDOM:
            case MusicService.COMMAND_UNKNOWN:
            case MusicService.COMMAND_CHECK_IS_PLAYING:
            default:
                break;
        }
        sendBroadcast(intent);
    }

    //内部类，用于播放器状态更新的接收广播
    class StatusChangedReceiver extends BroadcastReceiver
    {
        public void onReceive(Context context, Intent intent)
        {
            //获取歌曲信息
            String musicName = intent.getStringExtra("musicName");
            String musicArtist = intent.getStringExtra("musicArtist");
            //获取播放器状态
            status = intent.getIntExtra("status", -1);
            switch (status)
            {
                //正在播放
                case MusicService.STATUS_PLAYING:
                    seekBarHandler.removeMessages(PROGRESS_INCREASE);
                    time = intent.getIntExtra("time", 0);
                    duration = intent.getIntExtra("duration", 0);
                    number = intent.getIntExtra("number", number);
                    //实现刷新列表，将播放的歌曲在当前页面置顶
                    //listView.setSelection(number);
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                    tv_total_time.setText(formatTime(duration));
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.pause);
                    //设置textview文字，提示已经播放的歌曲
                    MainActivity.this.setTitle("正在播放:" + musicName + " - " + musicArtist);
                    break;
                //暂停
                case MusicService.STATUS_PAUSED:
                    seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                //停止
                case MusicService.STATUS_STOPPED:
                    time = 0;
                    duration = 0;
                    tv_current_time.setText(formatTime(time));
                    tv_total_time.setText(formatTime(duration));
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle("MusicPlayer");
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                //歌曲完成
                case MusicService.STATUS_COMPLETED:
                    number = intent.getIntExtra("number", 0);
                    switch (playmode)
                    {
                        //顺序播放
                        case MainActivity.MODE_LIST_SEQUENCE:
                            if (number == MusicList.getMusicList().size() - 1)
                                sendBroadcastOnCommand(MusicService.STATUS_STOPPED);
                            else
                                sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                            break;
                        //单曲循环
                        case MainActivity.MODE_SINGLE_CYCLE:
                            sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                            break;
                        //列表循环
                        case MainActivity.MODE_LIST_CYCLE:
                            if (number == MusicList.getMusicList().size() - 1)
                            {
                                number =0;
                                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                            }
                            else
                                sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                            break;
                        case MainActivity.MODE_LIST_RANDOM:
                            sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
                            break;
                        default:
                            break;
                    }
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle("MusicPlayer");
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                default:
                    break;
            }
        }
    }

    //格式化时间
    private String formatTime(int msec)
    {
        int minute = msec / 1000 / 60;
        int second = msec / 1000 % 60;
        String minuteString;
        String secondString;
        if (minute < 10)
        {
            minuteString = "0" + minute;
        } else {
            minuteString = "" + minute;
        }
        if (second < 10)
        {
            secondString = "0" + second;
        } else {
            secondString = "" + second;
        }
        return minuteString + ":" + secondString;
    }

    //进度条
    private void initSeekBarHandler()
    {
        seekBarHandler = new Handler() {
            public void handleMessage(Message msg)
            {
                super.handleMessage(msg);
                switch (msg.what)
                {
                    case PROGRESS_INCREASE:
                        if (seekBar.getProgress() < duration)
                        {
                            //进度条前进一秒
                            seekBar.setProgress(time);
                            //seekBar.incrementProgressBy(1000);
                            seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            //修改显示当前进度的文本
                            tv_current_time.setText(formatTime(time));
                            time += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        //重置进度条画面
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        tv_current_time.setText("00:00");
                        break;
                }
            }
        };
    }

    //创建菜单
    public boolean onCreateOptionsMenu(Menu menu)
    {
        this.getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /*处理菜单点击事件*/
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch(item.getItemId())
        {
            //主题
            case R.id.menu_theme:
                new AlertDialog.Builder(this).setTitle("请选择主题").
                        setItems(R.array.theme, new android.content.DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int which)
                            {
                                String theme = PropertyBean.THEMES[which];
                                MainActivity.this.setTheme(theme);
                                PropertyBean property = new PropertyBean(MainActivity.this);
                                property.setAndSaveTheme(theme);
                            }
                        }).show();
                break;
            //关于应用
            case R.id.menu_about:
                new AlertDialog.Builder(this).setTitle("MusicPlayer")
                        .setMessage(R.string.about2).show();
                break;
            //退出
            case R.id.menu_quit:
                new AlertDialog.Builder(this).setTitle(R.string.quit).setMessage(R.string.quit_message).
                        setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1)
                    {
                        Intent intent=new Intent(MainActivity.this, MusicService.class);
                        stopService(intent);
                        finish();
                    }
                }).setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                }).show();
                break;
            //播放模式
            case R.id.menu_playmode:
                String[] mode = new String[] { "顺序播放", "单曲循环", "列表循环","随机播放" };
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("播放模式");
                builder.setSingleChoiceItems(mode, playmode,//默认选择的序号
                    new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1)
                        {
                            playmode = arg1;
                        }
                    });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1)
                    {
                        play=playmode;
                        switch (playmode)
                        {
                            case 0:
                                playmode = MainActivity.MODE_LIST_SEQUENCE;
                                imgBtn_Mode.setBackgroundResource(R.drawable.button_list_sequence);
                                Toast.makeText(getApplicationContext(),R.string.sequence, Toast.LENGTH_SHORT).show();
                                break;
                            case 1:
                                playmode = MainActivity.MODE_SINGLE_CYCLE;
                                imgBtn_Mode.setBackgroundResource(R.drawable.button_single_cycle);
                                Toast.makeText(getApplicationContext(), R.string.singlecycle, Toast.LENGTH_SHORT).show();
                                break;
                            case 2:
                                playmode = MainActivity.MODE_LIST_CYCLE;
                                imgBtn_Mode.setBackgroundResource(R.drawable.button_list_cycle);
                                Toast.makeText(getApplicationContext(), R.string.listcycle, Toast.LENGTH_SHORT).show();
                                break;
                            case 3:
                                playmode=MainActivity.MODE_LIST_RANDOM;
                                imgBtn_Mode.setBackgroundResource(R.drawable.button_list_random);
                                Toast.makeText(getApplicationContext(),R.string.random,Toast.LENGTH_SHORT).show();
                            default:
                                break;
                        }
                    }
                });
                builder.create().show();
                break;
            //睡眠模式
            case R.id.menu_sleep:
                showSleepDialog();
                break;
            case R.id.menu_lrc:
                Intent intent=new Intent(MainActivity.this,LrcActivity.class);
                startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //设置Activity的主题，包括修改背景图片等等
    private void setTheme(String theme) {
        if ("彩色".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_color);
        } else if ("花朵".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_digit_flower);
        } else if ("群山".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_mountain);
        } else if ("小狗".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_running_dog);
        } else if ("冰雪".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_snow);
        } else if ("女孩".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_music_girl);
        } else if ("朦胧".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_blur);
        }
    }

    //双击退出
    private void exitByDoubleClick()
    {
        Timer timer = null;
        if(isExit == false)
        {
            isExit = true;		//准备退出
            Toast.makeText(this, "再按一次退出程序！", Toast.LENGTH_SHORT).show();
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run()
                {
                    isExit = false;
                }
            }, 2000);   //2 秒后会执行 run函数的内容，如果2秒内没有按下返回键，则启动定时器修改isExit的值
        }
        else
        {
            Intent intent=new Intent(MainActivity.this,MusicService.class);
            stopService(intent);
            finish();
        }
    }

    //交互
    @Override
    protected void onResume()
    {
        super.onResume();
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
        PropertyBean propertyBean = new PropertyBean(MainActivity.this);
        String theme = propertyBean.getTheme();
        //设置activity的主题
        setTheme(theme);
        //音量控制
        audio_Control();
        //睡眠模式打开时显示图标，关闭时隐藏图标
        if(sleepmode == MainActivity.ISSLEEP)
        {
            iv_sleep.setVisibility(View.VISIBLE);
        } else {
            iv_sleep.setVisibility(View.INVISIBLE);
        }
    }

    //音量控制
    private void audio_Control()
    {
        //获取音量管理器
        final AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        //设置当前调整音量大小只是针对媒体音乐
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        //设置滑动条最大值
        final int max_progress = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        seekbar_vol.setMax(max_progress);
        //获取当前音量
        int progress = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekbar_vol.setProgress(progress);
        tv_vol .setText("音量： "+(progress*100/max_progress)+"%");
        seekbar_vol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar arg0) {
            }
            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
            }
            @Override
            public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2)
            {
                tv_vol .setText("音量： "+(arg1*100)/(max_progress)+"%");

                //调整音量
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, AudioManager.FLAG_PLAY_SOUND);
            }
        });
    }

    //重写onkeyDown函数用音量按键控制音量
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        int progress;
        switch(keyCode)
        {
            //双击返回键退出程序
            case KeyEvent.KEYCODE_BACK:
                exitByDoubleClick();
                break;
            //降低音量键
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                progress = seekbar_vol.getProgress();
                if(progress != 0)
                    seekbar_vol.setProgress(progress-1);
                return true;
            //提高音量键
            case KeyEvent.KEYCODE_VOLUME_UP:
                progress = seekbar_vol.getProgress();
                if(progress != seekbar_vol.getMax())
                    seekbar_vol.setProgress(progress+1);
                return true;
            default:
                break;
        }
        return false;
    }

    //睡眠模式
    private void showSleepDialog()
    {
        //先用getLayoutInflater().inflate方法获取布局，用来初始化一个View类对象
        final View userView = this.getLayoutInflater().inflate(R.layout.dialog, null);

        //通过View类的findViewById方法获取到组件对象
        final TextView tv_minute = (TextView)userView.findViewById(R.id.dialog_tv);
        final Switch switch1 = (Switch)userView.findViewById(R.id.dialog_switch);
        final SeekBar seekbar = (SeekBar)userView.findViewById(R.id.dialog_seekbar);

        tv_minute.setText("睡眠于:"+sleepminute+"分钟后");
        //根据当前的睡眠状态来确定Switch的状态
        if(sleepmode == MainActivity.ISSLEEP)
            switch1.setChecked(true);
        //初始状态
        seekbar.setMax(60);
        seekbar.setProgress(sleepminute);
        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar arg0) {
            }
            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
            }
            @Override
            public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2)
            {
                sleepminute = arg1;
                tv_minute.setText("睡眠于:"+sleepminute+"分钟");
            }
        });
        //触发选择按钮
        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1)
            {
                sleepmode = arg1;
            }
        });
        //定义定时器任务
        final TimerTask timerTask = new TimerTask() {
            @Override
            public void run()
            {
                Intent intent=new Intent(MainActivity.this,MusicService.class);
                stopService(intent);
                finish();
            }
        };
        //定义对话框以及初始化
        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("选择睡眠时间(0~60分钟)");
        //设置布局
        dialog.setView(userView);
        //设置取消按钮响应事件
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1)
            {
                arg0.dismiss();
            }
        });
        //设置重置按钮响应时间
        dialog.setNeutralButton("重置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1)
            {
                if(sleepmode == MainActivity.ISSLEEP)
                {
                    timerTask.cancel();
                    if(timer_sleep != null)
                        timer_sleep.cancel();
                }
                sleepmode = MainActivity.NOTSLEEP;
                sleepminute = 20;
                iv_sleep.setVisibility(View.INVISIBLE);
            }
        });
        //设置确定按钮响应事件
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1)
            {
                if(sleepmode == MainActivity.ISSLEEP)
                {
                    timer_sleep = new Timer();
                    int time =seekbar.getProgress();
                    //启动任务，time*60*1000毫秒后执行
                    timer_sleep.schedule(timerTask, time*60*1000);
                    iv_sleep.setVisibility(View.VISIBLE);
                }
                else
                {
                    //取消任务
                    timerTask.cancel();
                    if(timer_sleep != null)
                        timer_sleep.cancel();
                    arg0.dismiss();
                    iv_sleep.setVisibility(View.INVISIBLE);
                }
            }
        });
        dialog.show();
    }

    @Override
    protected void onDestroy()
    {
        if (status == MusicService.STATUS_STOPPED)
        {
            stopService(new Intent(this, MusicService.class));
        }
        super.onDestroy();
    }
}
